package dao

import (
	"backend/app/dao/mysql"
	"backend/app/model"
	"encoding/json"

	"go.uber.org/zap"
)

func CheckMenuIsExist(menuId int32) (bool, error) {
	return mysql.CheckMenuIsExist(menuId)
}

func SaveMenumItem(menuItem *model.Menu) error {
	isExist, dErr := mysql.CheckMenuIsExist(menuItem.MenuId)
	if dErr != nil {
		return dErr
	}
	if isExist {
		return mysql.UpdateMenuItem(menuItem)
	} else {
		return mysql.InsertMenuItem(menuItem)
	}
}

func DeleteMenuItem(menuId int32) error {
	return mysql.DeleteMenuItem(menuId)
}

func GetMenuTree() ([]model.MenuTreeShow, error) {
	return GetMenuTreeByParentId(0)
}

func GetMenuTreeByParentId(parentId int32) ([]model.MenuTreeShow, error) {
	menuItems, err := mysql.QueryMenuItemByParentId(parentId)
	if err != nil {
		return nil, err
	}
	if len(menuItems) == 0 {
		return nil, nil
	}
	menuTree := []model.MenuTreeShow{}
	for _, menuItem := range menuItems {
		showOne := model.MenuTreeShow{}
		showOne.MenuId = menuItem.MenuId
		showOne.Name = menuItem.Name
		showOne.Redirect = menuItem.Redirect
		showOne.Path = menuItem.Path
		showOne.Component = menuItem.Component
		showOne.ParentId = menuItem.ParentId
		showOne.Meta = model.MenuMeta{}
		if err := json.Unmarshal([]byte(menuItem.Meta), &showOne.Meta); err != nil {
			zap.L().Error(" meta unmarshal is failed, err ", zap.Error(err))
		}
		children, err := GetMenuTreeByParentId(menuItem.MenuId)
		if err == nil {
			showOne.Children = children
		}
		menuTree = append(menuTree, showOne)
	}
	return menuTree, nil
}
